//
//  SettingViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/11/17.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  设置页面

import UIKit

protocol SettingViewControllerDelegate {
    func back()
}

class SettingViewController: TableBaseViewController,SettingCellDelegate {

    var delegate : SettingViewControllerDelegate?
    
    //验证是够第三方授权是否绑定手机,并且是否设置密码
    
    
    //表格数据源
    lazy var dataArr : NSMutableArray = {
        var data = NSMutableArray()
        data = ["编辑个人资料","密码修改","绑定手机号","收货地址"]

        return data
    }()
    
    //图片
    lazy var imgName : NSMutableArray = {
        var data = NSMutableArray()
        data = ["perInfo","password","phone","address"]
        
        return data
    }()
    
    //导航栏设置还原
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
        
//        
//        if PersonInfoModel.shared.bindPhone != "" {
//            if PersonInfoModel.shared.bindPhone == "false" {
//                
//            } else {
        
                guard let personData = localSave.object(forKey: thirdLoginInfo) as? NSDictionary else {
                    return
                }
                
                guard let telNum = personData["password"] as? NSString else {
                    return
                }

                //判断手机号是否为空
                if telNum == "false" {
                     dataArr = ["编辑个人资料","设置绑定密码","绑定手机号","收货地址"]
                } else {
                    dataArr = ["编辑个人资料","密码修改","绑定手机号","收货地址"]
                }
                
//            }
//        
//        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //标题
        self.navigationItem.title = "设置"

        
        //设置表格样式
        setStyle()
    }

}

// MARK:- 表格代理和方法
extension SettingViewController {
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        switch section {
        case 0:
            return dataArr.count
        default:
            return 1
        }
    }
    
    //设置section 间距
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        return 1
    }
    
    
    //设置数据源
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as? SettingCell
        if cell == nil {
            cell = SettingCell(style: .default, reuseIdentifier: "cellID")
            tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            //监听代理
            cell?.delegate = self
            cell?.imgView.image = UIImage.init(named: imgName[indexPath.row] as! String)
        }

        switch indexPath.section {
            //第一组时，显示
        case 0:
            cell?.btn.isHidden = true
            cell?.nameLabel.text = dataArr[indexPath.row] as? String
            //第二组时，不显示
        default:
            cell?.backgroundColor = UIColor.clear
            cell?.line.isHidden = true
            cell?.imgView.isHidden = true
            cell?.nameLabel.isHidden = true
            cell?.disclosureImg.isHidden = true
            break
        }

        return (cell)!
   
    }
    
    
    
    //设置行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击了 ",indexPath.row)
        switch indexPath.row {
            //编辑个人资料
        case 0:
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(PersonInfoViewController(), animated: true)
//            self.hidesBottomBarWhenPushed = false
            break
            
            //密码修改
        case 1:
            
            print(localSave.object(forKey: thirdLoginInfo) as Any)
            
            //先判断单例是否为空
            if PersonInfoModel.shared.bindPhone != "" {
                
                
                
                //判断单例是否存储对应的值
                if PersonInfoModel.shared.bindPhone == "true" {
                    self.hidesBottomBarWhenPushed = true

                    self.navigationController?.pushViewController(SetThirdPassVC(), animated: true)
                    
                    return
                }
            }
            
            
            if localSave.object(forKey: "bindPhone") != nil {
                self.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(SetThirdPassVC(), animated: true)
                return
            }

            
            guard let personData = localSave.object(forKey: thirdLoginInfo) as? NSDictionary else {
                //没有第三方登陆资料进入默认设置密码页面
                self.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(ChagePassViewController(), animated: true)
                
                return
            }
        
            //取出密码
            guard let passs = personData["password"] as? NSString else {
                
                return
            }
        
            //取出号码
            guard let phone = personData["phone"] as? String else {
                return
            }
        
        
            if phone == "" || phone.characters.count == 0 {
                CustomAlertView.shared.alertWithTitle(strTitle: "请先绑定手机号")
            }

            //判断手机号是否为空
            if passs == "false" {
                self.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(SetThirdPassVC(), animated: true)
            } else {
                self.hidesBottomBarWhenPushed = true

                self.navigationController?.pushViewController(ChagePassViewController(), animated: true)
                
            }
        break
            //绑定手机号
        case 2:
            
            //检测单例中是否有值，已绑定手机号码，若单例没有，从本地取判断
            //1.PersonInfoModel.shared.bindPhone = list["password"] as? String（值为false）,可以单击跳转到绑定手机号码界面,若已绑定，提示已绑定

                if PersonInfoModel.shared.bindPhone == "true" {
                    
                    if localSave.object(forKey: "bindPhone") != nil {
                        var bindPhone = localSave.object(forKey: "bindPhone") as! NSString
                        //替换指定字符为****
                        let range = NSMakeRange(4, 4)
                        
                        bindPhone = bindPhone.replacingCharacters(in: range, with: "****") as NSString
                        
                        let alertView = UIAlertController.init(title: "提示", message: "已绑定手机号:\(bindPhone)", preferredStyle: .alert)
                        alertView.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
                        
                        self.present(alertView, animated: true, completion: nil)
                    }
                    
                }


                guard let personData = localSave.object(forKey: thirdLoginInfo) as? NSDictionary else {
                    
                    guard let personData = localSave.object(forKey: personInfo) as? NSDictionary else {
                        return
                    }
                    
                    guard var telNum = personData["phone"] as? NSString else {
                        
                        return
                    }
                    
                    //判断手机号是否为空
                    if telNum == "" {
                        self.hidesBottomBarWhenPushed = true

                        self.navigationController?.pushViewController(BindPhoneNumViewController(), animated: true)
                        
                    } else {
                        //替换指定字符为****
                        let range = NSMakeRange(4, 4)
                        
                        telNum = telNum.replacingCharacters(in: range, with: "****") as NSString
                        
                        let alertView = UIAlertController.init(title: "提示", message: "已绑定手机号:\(telNum)", preferredStyle: .alert)
                        alertView.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
                        
                        self.present(alertView, animated: true, completion: nil)
                    }

                    return
                }
                
                guard var telNum = personData["phone"] as? NSString else {
                    
                    return
                }
                
                print(telNum)
                
                
                //判断手机号是否为空
                if telNum == "" {
                    self.hidesBottomBarWhenPushed = true

                    self.navigationController?.pushViewController(BindPhoneNumViewController(), animated: true)
                    
                } else {
                    //替换指定字符为****
                    let range = NSMakeRange(4, 4)
                    
                    telNum = telNum.replacingCharacters(in: range, with: "****") as NSString
                    
                    let alertView = UIAlertController.init(title: "提示", message: "已绑定手机号:\(telNum)", preferredStyle: .alert)
                    alertView.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
                    
                    self.present(alertView, animated: true, completion: nil)
                }

//                }
//            }
            
            
            break
            
        //收货地址
        case 3:
            self.hidesBottomBarWhenPushed = true

            self.navigationController?.pushViewController(GetGoodsVieController(), animated: true)
            break

        default:
            break
        }
    }

}



// MARK:- 设置表格样式
extension SettingViewController {
   fileprivate func setStyle() -> Void {
    
        tableView = UITableView(frame: self.view.bounds, style: .grouped)
    }
}


// MARK:- 监听代理函数
extension SettingViewController {
    func showLogVC() {
        print("退出出来")
        
        
    }
    
    func logoutSel() {
        let alert = UIAlertController.init(title: "提示", message: "您确定退出么?", preferredStyle: .alert)
        
        
        alert.addAction(UIAlertAction.init(title: "退出", style: .destructive, handler: { (nil) in
            
            logoutModel.shared.logoutSEL { (result) in
                print(result)
                if result == "退出成功" {
                    
                    print(localSave.object(forKey: userToken) as Any)
                    
                    
                    //删除本地token
                    localSave.removeObject(forKey: userToken)
                    localSave.synchronize()
                    
                    //清楚本地数据
                    if let appDomain = Bundle.main.bundleIdentifier {
                        UserDefaults.standard.removePersistentDomain(forName: appDomain)
                    }
                    
                    CustomAlertView.shared.alertWithTitle(strTitle: logoutSuccess)
                    
                    //延迟一秒执行，避免退出的dismissViewController 造成主线程阻塞
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                        let mainVC = MainViewController()
                        
                        mainVC.mvc = MyVC()
                        
                        UIApplication.shared.keyWindow?.rootViewController = mainVC
                    }
                } else if result == "该账号已在异地登录，请重新登录" {
                    
                    CustomAlertView.shared.alertWithTitle(strTitle: logoutSuccess)
                    
                    //延迟一秒执行，避免退出的dismissViewController 造成主线程阻塞
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
                        let mainVC = MainViewController()
                        
                        mainVC.mvc = MyVC()
                        
                        UIApplication.shared.keyWindow?.rootViewController = mainVC
                    }

                    
                    //清楚本地数据
                    if let appDomain = Bundle.main.bundleIdentifier {
                        UserDefaults.standard.removePersistentDomain(forName: appDomain)
                    }
                }
                
            }

        }))
        
        alert.addAction(UIAlertAction.init(title: "取消", style: .default, handler: nil))
        
                self.present(alert, animated: true, completion: nil)

    }
}




